package v1

import (
	"fmt"
	"github.com/gofiber/fiber/v2"
	"github.com/levigross/grequests"
	uuid "github.com/satori/go.uuid"
	"net/url"
	"no-watermark/app/logic"
)

type Index struct {
}

// NewRouter 本页面相关路由
func (c *Index) NewRouter(g fiber.Router) {
	g.Get("/", c.Index)                //首页
	g.Post("/api/parse", c.Parse)      //解析
	g.Get("/api/download", c.Download) //下载
}

// Download 下载页面
func (c *Index) Download(ctx *fiber.Ctx) error {
	videoUrl := ctx.FormValue("url")
	//log.Println(videoUrl)
	videoUrl, _ = url.QueryUnescape(videoUrl)
	filename := uuid.NewV4().String() + ".mp4"

	res, _ := grequests.Get(videoUrl, &grequests.RequestOptions{
		Headers: map[string]string{
			"User-Agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Mobile Safari/537.36",
		},
	})
	defer res.Close()
	ctx.Set("Content-Description", "File Transfer")
	ctx.Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", filename))
	ctx.Set("Content-Type", "application/octet-stream")
	ctx.Set("Content-Type", "video/mp4")
	ctx.Set("Expires", "0")
	ctx.Set("Cache-Control", "must-revalidate, post-check=0, pre-check=0")
	ctx.Set("Pragma", "public")
	ctx.Set("Content-Transfer-Encoding", "binary")
	_, _ = ctx.Write(res.Bytes())
	return nil
}

// Index 页面
func (c *Index) Index(ctx *fiber.Ctx) error {
	return ctx.Render("index", fiber.Map{
		"title": "视频去水印",
	})
}

// Parse 视频统一水印去除
func (c *Index) Parse(ctx *fiber.Ctx) error {
	txt := ctx.FormValue("txt")
	//log.Println(string(ctx.Body()))
	videoUrl, err := logic.GetVideoURL(txt)
	if err != nil {
		return ctx.JSON(fiber.Map{
			"code": "500",
			"msg":  fmt.Sprintf("解析失败,原因：%v", err),
		})
	}

	//filename, err := logic.GetFilename("video")
	//if err != nil {
	//	return ctx.JSON(fiber.Map{
	//		"code": "500",
	//		"msg":  fmt.Sprintf("解析失败,原因：%v", err),
	//	})
	//}
	//
	////下载文件
	//err = logic.DownloadFile(filename, videoUrl)
	//log.Println(err)
	//if err != nil {
	//	return ctx.JSON(fiber.Map{
	//		"code": "500",
	//		"msg":  "下载视频失败",
	//	})
	//}

	return ctx.JSON(fiber.Map{
		"code": "200",
		"msg":  "解析成功",
		//"url":  "/" + filename,
		"url": videoUrl,
	})
}
